package com.my.socket.nio.v22;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector acceptSelector;
    private Selector readWriteSelector;
    private ServerSocketChannel serverSocketChannel;

    public Server(String host, int port) throws Exception {
        this.acceptSelector = Selector.open();
        this.readWriteSelector = Selector.open();
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
    }

    public void startup() throws Exception {
        new Thread(new AcceptTask(this.acceptSelector, this.readWriteSelector)).start();
        new Thread(new ReadWriteTask(this.readWriteSelector)).start();
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 9999;
        Server server = new Server(host, port);
        server.startup();
        LOGGER.info("listen at {}:{}", host, port);
    }
}
